<template>
  <div class="purchased-items-page">
    <HeaderNav v-if="!isAdmin" />
    <AdminHeaderNav v-if="isAdmin" />

    <div class="purchased-container">
      <div class="page-header">
        <h2>已买到的宝贝</h2>
      </div>

      <div class="items-content" v-loading="loading">
        <!-- 订单列表 -->
        <div v-if="orderList.length > 0" class="order-list">
          <div v-for="order in orderList" :key="order.id" class="order-card">
            <div class="order-header">
              <span class="order-no">订单号：{{ order.orderId }}</span>
              <span class="order-time">{{ order.createTime }}</span>
            </div>

            <div class="order-body">
              <div class="item-image" v-if="order.itemImg">
                <el-image
                  :src="order.itemImg"
                  :alt="order.itemName"
                  fit="cover"
                  class="product-img"
                  :preview-src-list="[order.itemImg]"
                  loading="lazy"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
              
              <div class="item-info">
                <div class="item-name">{{ order.itemName }}</div>
                <div class="merchant-info" v-if="order.merchantName">
                  <div class="merchant-content">
                    <div class="merchant-logo" v-if="order.logo">
                      <el-image
                        :src="order.logo"
                        :alt="order.merchantName"
                        fit="cover"
                        class="logo-img"
                      >
                        <template #error>
                          <div class="logo-placeholder">
                            <el-icon><Shop /></el-icon>
                          </div>
                        </template>
                      </el-image>
                    </div>
                    <div class="merchant-name">
                      <el-icon v-if="!order.logo"><Shop /></el-icon>
                      <span>{{ order.merchantName }}</span>
                    </div>
                  </div>
                  <el-tag 
                    :type="getStatusType(order.status)" 
                    size="large"
                    class="status-tag"
                  >
                    {{ getStatusText(order.status) }}
                  </el-tag>
                </div>
                <div class="spec-and-total">
                  <div class="item-spec" v-if="order.spec">规格：{{ formatSpec(order.spec) }}</div>
                  <div class="total-price">总价格：{{ (order.price * order.num).toFixed(2) }}</div>
                </div>
                <div class="item-details">
                  <span>单价：￥{{ order.price }}</span>
                  <span>数量：{{ order.num }}</span>
                </div>
              </div>

              <div class="order-actions">
                <el-button 
                  v-if="order.status === 0" 
                  type="danger" 
                  size="small"
                  @click="payOrder(order.id)"
                >
                  立即支付
                </el-button>
                <el-button 
                  v-if="order.status === 2" 
                  type="primary" 
                  size="small"
                  @click="confirmReceipt(order.id)"
                >
                  确认收货
                </el-button>
                <el-button 
                  v-if="order.status === 4" 
                  type="warning" 
                  size="small"
                  @click="applyRefund(order.id)"
                >
                  申请退款
                </el-button>
                <el-button 
                  v-if="order.status === 5" 
                  type="info" 
                  size="small"
                  disabled
                >
                  退款处理中
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-icon class="empty-icon"><ShoppingBag /></el-icon>
          <p>暂无购买记录</p>
          <el-button type="primary" @click="goShopping">去逛逛</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ShoppingBag, Shop, Picture } from '@element-plus/icons-vue'
import HeaderNav from '../../components/layout/HeaderNav.vue'
import AdminHeaderNav from '../../components/layout/AdminHeaderNav.vue'
import { useUserStore } from '../../stores/user'
import { getPurchasedItemsService, confirmReceiptService, applyRefundService } from '../../api/order'

const router = useRouter()
const userStore = useUserStore()

interface DetailOrder {
  id: number
  orderId: string
  itemName: string
  itemImg: string
  merchantName: string
  logo: string
  num: number
  price: number
  spec: string
  status: number
  createTime: string
  updateTime: string
}

const loading = ref(false)
const orderList = ref<DetailOrder[]>([])

const isAdmin = computed(() => userStore.isAdmin)

// 获取订单状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: '未支付',
    1: '未发货',
    2: '已发货',
    3: '已到达',
    4: '已收货',
    5: '申请退款',
    6: '拒绝退款',
    7: '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 获取订单状态类型
const getStatusType = (status: number): string => {
  const typeMap: Record<number, string> = {
    0: 'danger',
    1: 'warning',
    2: 'primary',
    3: 'success',
    4: 'success',
    5: 'warning',
    6: 'danger',
    7: 'info'
  }
  return typeMap[status] || 'info'
}

// 格式化规格字段
const formatSpec = (spec: string): string => {
  try {
    const specObj = JSON.parse(spec)
    return Object.entries(specObj)
      .map(([key, value]) => `${key}: ${value}`)
      .join(', ')
  } catch (error) {
    // 如果不是 JSON 格式，直接返回原字符串
    return spec
  }
}

// 支付订单
const payOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要支付此订单吗？',
      '支付确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用支付接口
    console.log('支付订单 ID:', orderId)
    ElMessage.success('跳转到支付页面...')
    // 这里可以跳转到支付页面
    // router.push(`/payment/${orderId}`)
  } catch (error) {
    // 用户取消操作
  }
}

// 加载已购买商品列表
const loadPurchasedItems = async () => {
  loading.value = true
  try {
    const res: any = await getPurchasedItemsService()
    if (res.code === 0) {
      orderList.value = res.data || []
    } else {
      ElMessage.error(res.message || '加载失败')
    }
  } catch (error) {
    console.error('加载已购买商品失败:', error)
    ElMessage.error('加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 确认收货
const confirmReceipt = async (orderId: number) => {
  try {
    await ElMessageBox.confirm(
      '确认已收到商品吗？',
      '确认收货',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用确认收货接口
    const res: any = await confirmReceiptService(orderId)
    if (res.code === 0) {
      ElMessage.success('确认收货成功')
      loadPurchasedItems()
    } else {
      ElMessage.error(res.message || '确认收货失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败，请稍后重试')
    }
  }
}

// 申请退款
const applyRefund = async (orderId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要申请退款吗？',
      '申请退款',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用申请退款接口
    const res: any = await applyRefundService(orderId)
    if (res.code === 0) {
      ElMessage.success('退款申请已提交')
      loadPurchasedItems()
    } else {
      ElMessage.error(res.message || '申请退款失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('申请退款失败:', error)
      ElMessage.error('申请退款失败，请稍后重试')
    }
  }
}

// 去购物
const goShopping = () => {
  router.push('/layout')
}

onMounted(() => {
  loadPurchasedItems()
})
</script>

<style scoped lang="scss">
.purchased-items-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.purchased-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.page-header {
  background: white;
  padding: 1.5rem 2rem;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  h2 {
    font-size: 1.5rem;
    color: #303133;
    margin: 0;
  }
}

.items-content {
  min-height: 400px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.order-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;

  &:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
  }

  .order-header {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1.2rem 1.5rem;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-bottom: 1px solid #e9ecef;

    .order-no {
      flex: 1;
      color: #495057;
      font-size: 0.9rem;
      font-weight: 500;
    }

    .order-time {
      color: #6c757d;
      font-size: 0.85rem;
    }
  }

  .order-body {
    display: flex;
    align-items: flex-start;
    padding: 1.5rem;
    gap: 1rem;

    .item-image {
      flex-shrink: 0;
      width: 100px;
      height: 100px;
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #f0f0f0;

      .product-img {
        width: 100%;
        height: 100%;
        cursor: pointer;
      }

      .image-slot {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        color: #909399;
        font-size: 1.5rem;
      }
    }

    .item-info {
      flex: 1;
      min-width: 0;

      .item-name {
        font-size: 1rem;
        color: #303133;
        font-weight: 500;
        line-height: 1.4;
        word-break: break-word;
        margin: 0 0 0.8rem 0;
      }

      .merchant-info {
        display: grid;
        grid-template-columns: 1fr 120px;
        align-items: center;
        gap: 1rem;
        margin-bottom: 0.6rem;

        .merchant-content {
          display: flex;
          align-items: center;
          gap: 0.5rem;
        }

        .status-tag {
          font-size: 0.9rem;
          font-weight: 600;
          padding: 0.4rem 0.8rem;
          border-radius: 6px;
          border: none;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          white-space: nowrap;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
          justify-self: center;
        }

        .merchant-logo {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          overflow: hidden;
          border: 1px solid #e4e7ed;
          flex-shrink: 0;

          .logo-img {
            width: 100%;
            height: 100%;
          }

          .logo-placeholder {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
            background: #f5f7fa;
            color: #909399;
            font-size: 0.7rem;
          }
        }

        .merchant-name {
          display: flex;
          align-items: center;
          gap: 0.3rem;
          color: #409eff;
          font-size: 0.85rem;

          .el-icon {
            font-size: 0.9rem;
          }
        }
      }

      .spec-and-total {
        display: grid;
        grid-template-columns: 1fr 120px;
        align-items: center;
        margin-bottom: 0.5rem;
        gap: 1rem;

        .item-spec {
          color: #909399;
          font-size: 0.85rem;
        }

        .total-price {
          color: #e74c3c;
          font-weight: 600;
          font-size: 0.9rem;
          padding: 0.4rem 0.8rem;
          background: #ffeaea;
          border-radius: 6px;
          border: none;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          white-space: nowrap;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
          justify-self: center;
        }
      }

      .item-details {
        display: flex;
        gap: 1.5rem;
        font-size: 0.9rem;
        color: #6c757d;

        span {
          padding: 0.2rem 0.5rem;
          background: #f8f9fa;
          border-radius: 4px;
          font-size: 0.85rem;
        }
      }
    }

    .order-actions {
      display: flex;
      flex-direction: column;
      gap: 0.5rem;
      min-width: 130px;
      flex-shrink: 0;
      align-self: flex-start;

      .el-button {
        border-radius: 6px;
        font-size: 0.85rem;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .empty-icon {
    font-size: 5rem;
    color: #dcdfe6;
    margin-bottom: 1rem;
  }

  p {
    color: #909399;
    font-size: 1rem;
    margin-bottom: 1.5rem;
  }
}

@media (max-width: 768px) {
  .purchased-container {
    padding: 1rem;
  }

  .page-header {
    padding: 1rem;

    h2 {
      font-size: 1.2rem;
    }
  }

  .order-card {
    .order-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 0.5rem;
    }

    .order-body {
      flex-direction: column;
      align-items: flex-start;
      gap: 1rem;

      .item-image {
        width: 80px;
        height: 80px;
        align-self: center;
      }

      .item-info {
        width: 100%;

        .item-name {
          font-size: 0.9rem;
          margin: 0 0 0.6rem 0;
        }

        .merchant-info {
          flex-direction: column;
          align-items: flex-start;
          gap: 0.5rem;

          .merchant-content {
            width: 100%;

            .merchant-logo {
              width: 20px;
              height: 20px;
            }

            .merchant-name {
              font-size: 0.8rem;
            }
          }

          .status-tag {
            align-self: flex-end;
            font-size: 0.8rem;
            font-weight: 600;
            padding: 0.3rem 0.6rem;
            border-radius: 6px;
            border: none;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }

        .spec-and-total {
          display: grid;
          grid-template-columns: 1fr;
          gap: 0.3rem;

          .item-spec {
            font-size: 0.8rem;
            width: 100%;
          }

          .total-price {
            justify-self: center;
            font-size: 0.8rem;
            font-weight: 600;
            padding: 0.3rem 0.6rem;
            background: #ffeaea;
            border-radius: 6px;
            border: none;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }

        .item-details {
          flex-wrap: wrap;
          gap: 0.8rem;

          span {
            font-size: 0.8rem;
            padding: 0.15rem 0.4rem;
          }
        }
      }

      .order-actions {
        width: 100%;
        flex-direction: row;
        flex-wrap: wrap;
        gap: 0.5rem;

        .el-button {
          flex: 1;
          min-width: 80px;
        }
      }
    }
  }
}
</style>
